//
//  FirendCirLocalPathdb.m
//  tcpoctest
//
//  Created by gump on 4/16/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "FirendCirLocalPathdb.h"
#import "FirCirLocalInfo.h"
#import "FirCirLocalResourceDataSource.h"

@implementation FirendCirLocalPathdb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists fircirlocal(resourceID text,\
url text,localpath text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);

}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM fircirlocal"];
    FMResultSet *s = [db executeQuery:strsql];
    
    [[DataControl shareControl].fcLocalRecDS RemoveAllLocalRs];
    
    while ([s next])
    {
        FirCirLocalInfo *fclinfo = [[FirCirLocalInfo alloc] init];
        fclinfo.resourceID = [s stringForColumn:@"resourceID"];
        fclinfo.url = [s stringForColumn:@"url"];
        fclinfo.localpath = [s stringForColumn:@"localpath"];
        
        [[DataControl shareControl].fcLocalRecDS AddLocalRs:fclinfo];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertLocalPath:(FirCirLocalInfo *)fclinfo
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM fircirlocal where resourceID = '%@'",
                        fclinfo.resourceID];
    
    FMResultSet *s = [db executeQuery:strsql];
    
    
        if([s next])
        {
            strsql = [NSString stringWithFormat:@"update fircirlocal \
set url = '%@',localpath = '%@' WHERE resourceID = '%@'",
                      fclinfo.url
                      ,fclinfo.localpath
                      ,fclinfo.resourceID];
        }
        else
        {
            strsql = [NSString stringWithFormat:@"INSERT INTO fircirlocal \
(resourceID,url,localpath)\
VALUES ('%@','%@','%@')"
                      ,fclinfo.resourceID
                      ,fclinfo.url
                      ,fclinfo.localpath];
        }
        
        [db executeUpdate:strsql];

    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)deleteByID:(NSString *)newid
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"DELETE FROM fircirlocal WHERE resourceID = '%@'"
                        ,newid];
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
